package com.chuanye.jiguangimdemo.activitys;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.activeandroid.query.Update;
import com.chuanye.jiguangimdemo.R;
import com.chuanye.jiguangimdemo.app.MyApplication;
import com.chuanye.jiguangimdemo.database.FriendEntry;
import com.chuanye.jiguangimdemo.entity.Event;
import com.chuanye.jiguangimdemo.entity.EventType;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Date;

import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.callback.GetAvatarBitmapCallback;
import cn.jpush.im.android.api.callback.GetUserInfoCallback;
import cn.jpush.im.android.api.model.Conversation;
import cn.jpush.im.android.api.model.GroupInfo;
import cn.jpush.im.android.api.model.UserInfo;

/**
 * 好友详细资料
 */
public class FriendInfoActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "FriendInfoActivity";
    private Context mContext;

    private ImageView friendinfo_back_iv;
    private TextView friendinfo_username_tv;
    private ImageView friendinfo_icon_iv;
    private Button friendinfo_send_btn;
    private ImageView friendinfo_more_iv;
    private TextView friendinfo_nickname_tv;
    private TextView friendinfo_signature_tv;
    private TextView friendinfo_nick_tv;
    private TextView friendinfo_gender_tv;
    private TextView friendinfo_birthday_tv;
    private TextView friendinfo_address_tv;


    private String mTargetId;
    private String mTargetAppKey;
    private boolean mIsFromContact;
    private UserInfo mUserInfo;
    private long mGroupId;
    private String mTitle;//用于会话名
    private boolean mIsGetAvatar = false;
    private boolean mIsAddFriend = false;
    private boolean mIsFromSearch = false;
    private boolean mFromGroup = false;
    private String mUserID;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friend_info);
        mContext = this;

        mTargetId = getIntent().getStringExtra(MyApplication.TARGET_ID);
        mTargetAppKey = getIntent().getStringExtra(MyApplication.TARGET_APP_KEY);
        mUserID = getIntent().getStringExtra("targetId");
        if (mTargetAppKey == null) {
            mTargetAppKey = JMessageClient.getMyInfo().getAppKey();
        }
        int flags = getIntent().getFlags();

        mIsFromContact = getIntent().getBooleanExtra("fromContact", false);
        mIsFromSearch = getIntent().getBooleanExtra("fromSearch", false);
        mIsAddFriend = getIntent().getBooleanExtra("addFriend", false);
        mFromGroup = getIntent().getBooleanExtra("group_grid", false);
        initView();


        //从通讯录中点击过来
        if (mIsFromContact || mIsFromSearch || mFromGroup || mIsAddFriend) {
            updateUserInfo();
        } else {
            mGroupId = getIntent().getLongExtra(MyApplication.GROUP_ID, 0);
            Conversation conv;
            if (mGroupId == 0) {
                conv = JMessageClient.getSingleConversation(mTargetId, mTargetAppKey);
                mUserInfo = (UserInfo) conv.getTargetInfo();
            } else {
                conv = JMessageClient.getGroupConversation(mGroupId);
                GroupInfo groupInfo = (GroupInfo) conv.getTargetInfo();
                mUserInfo = groupInfo.getGroupMemberInfo(mTargetId, mTargetAppKey);
            }

            //设置数据
            initData(mUserInfo);
            updateUserInfo();
        }


    }

    private void initView() {
        //返回
        friendinfo_back_iv = findViewById(R.id.friendinfo_back_iv);
        friendinfo_back_iv.setOnClickListener(this);
        //更多
        friendinfo_more_iv = findViewById(R.id.friendinfo_more_iv);
        friendinfo_more_iv.setOnClickListener(this);
        //用户头像
        friendinfo_icon_iv = findViewById(R.id.friendinfo_icon_iv);
        friendinfo_icon_iv.setOnClickListener(this);
        //头像下的昵称 或备注名
        friendinfo_nickname_tv = findViewById(R.id.friendinfo_nickname_tv);
        //签名
        friendinfo_signature_tv = findViewById(R.id.friendinfo_signature_tv);
        //用户名
        friendinfo_username_tv = findViewById(R.id.friendinfo_username_tv);
        //昵称
        friendinfo_nick_tv = findViewById(R.id.friendinfo_nick_tv);
        //性别
        friendinfo_gender_tv = findViewById(R.id.friendinfo_gender_tv);
        //生日
        friendinfo_birthday_tv = findViewById(R.id.friendinfo_birthday_tv);
        //地区
        friendinfo_address_tv = findViewById(R.id.friendinfo_address_tv);


        //加好友按钮
        friendinfo_send_btn = findViewById(R.id.friendinfo_send_btn);
        friendinfo_send_btn.setOnClickListener(this);


    }

    /**
     * 设置数据
     */
    public void initData(UserInfo userInfo) {
        if (userInfo != null) {
            if (!TextUtils.isEmpty(userInfo.getAvatar())) {//好友头像
                userInfo.getAvatarBitmap(new GetAvatarBitmapCallback() {
                    @Override
                    public void gotResult(int status, String desc, Bitmap bitmap) {
                        if (status == 0) {
                            friendinfo_icon_iv.setImageBitmap(bitmap);
                        } else {
                            friendinfo_icon_iv.setImageResource(R.drawable.rc_default_portrait);
                        }
                    }
                });
            } else {
                friendinfo_icon_iv.setImageResource(R.drawable.rc_default_portrait);
            }
            String noteName = userInfo.getNotename();//备注
            String nickName = userInfo.getNickname();//昵称
            String userName = userInfo.getUserName();//用户名
            //有备注
            if (!TextUtils.isEmpty(noteName)) {
                friendinfo_nickname_tv.setText("备注名: " + noteName);
            }else if (TextUtils.isEmpty(noteName) && !TextUtils.isEmpty(nickName)) {//没有备注 有昵称
                friendinfo_nickname_tv.setText("昵称: " + nickName);
            }else {//没有备注名 没有昵称
                friendinfo_nickname_tv.setText("用户名: " + userName);
            }
            //签名
            if (!TextUtils.isEmpty(userInfo.getSignature())){
                friendinfo_signature_tv.setText(userInfo.getSignature());
            }else {
                friendinfo_signature_tv.setText("");
            }
            //用户名
            if (!TextUtils.isEmpty(userInfo.getUserName())){
                friendinfo_username_tv.setText(userInfo.getUserName());
            }else {
                friendinfo_username_tv.setText("");
            }
            //昵称
            if (!TextUtils.isEmpty(userInfo.getNickname())){
                friendinfo_nick_tv.setText(userInfo.getNickname());
            }else {
                friendinfo_nick_tv.setText("");
            }
            //性别
            if (userInfo.getGender() == UserInfo.Gender.male) {
                friendinfo_gender_tv.setText("男");
            } else if (userInfo.getGender() == UserInfo.Gender.female) {
                friendinfo_gender_tv.setText("女");
            } else {
                friendinfo_gender_tv.setText("未知");
            }
            //生日
            friendinfo_birthday_tv.setText(getBirthday(userInfo));
            //地区
            if (!TextUtils.isEmpty(userInfo.getAddress())){
                friendinfo_address_tv.setText(userInfo.getAddress());
            }else {
                friendinfo_address_tv.setText("");
            }



        }
    }
    public String getBirthday(UserInfo info) {
        long birthday = info.getBirthday();
        if (birthday == 0) {
            return "";
        }else {
            Date date = new Date(birthday);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            return dateFormat.format(date);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.friendinfo_back_iv://返回
                finish();
                break;
            case R.id.friendinfo_more_iv://更多
                Intent intent = new Intent();
                intent.setClass(mContext, FriendSettingActivity.class);
                intent.putExtra("userName", mUserInfo.getUserName());
                intent.putExtra("noteName", mUserInfo.getNotename());
                mContext.startActivity(intent);
                break;
            case R.id.friendinfo_send_btn: //发消息
               startChatActivity();
                break;
            case R.id.friendinfo_icon_iv://点击头像预览大图
                startBrowserAvatar();
                break;
        }
    }


    public void startChatActivity() {
        if (mIsFromContact || mIsAddFriend || mIsFromSearch || mFromGroup) {
            Intent intent = new Intent(this, ChatActivity.class);
            String title = mUserInfo.getNotename();
            if (TextUtils.isEmpty(title)) {
                title = mUserInfo.getNickname();
                if (TextUtils.isEmpty(title)) {
                    title = mUserInfo.getUserName();
                }
            }
            intent.putExtra(MyApplication.CONV_TITLE, title);
            intent.putExtra(MyApplication.TARGET_ID, mUserInfo.getUserName());
            intent.putExtra(MyApplication.TARGET_APP_KEY, mUserInfo.getAppKey());
            startActivity(intent);
        } else {
            if (mGroupId != 0) {
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra(MyApplication.TARGET_ID, mTargetId);
                intent.putExtra(MyApplication.TARGET_APP_KEY, mTargetAppKey);
                intent.setClass(this, ChatActivity.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent();
                intent.putExtra("returnChatActivity", true);
                intent.putExtra(MyApplication.CONV_TITLE, mTitle);
                setResult(MyApplication.RESULT_CODE_FRIEND_INFO, intent);
            }
        }
        Conversation conv = JMessageClient.getSingleConversation(mTargetId, mTargetAppKey);
        //如果会话为空，使用EventBus通知会话列表添加新会话
        if (conv == null) {
            conv = Conversation.createSingleConversation(mTargetId, mTargetAppKey);
            EventBus.getDefault().post(new Event.Builder()
                    .setType(EventType.createConversation)
                    .setConversation(conv)
                    .build());
        }
    }


    /**
     * 点击头像预览大图
     */
    public void startBrowserAvatar() {
        /*if (mUserInfo != null && !TextUtils.isEmpty(mUserInfo.getAvatar())) {
            if (mIsGetAvatar) {
                //如果缓存了图片，直接加载
                Bitmap bitmap = NativeImageLoader.getInstance().getBitmapFromMemCache(mUserInfo.getUserName());
                if (bitmap != null) {
                    Intent intent = new Intent();
                    intent.putExtra("browserAvatar", true);
                    intent.putExtra("avatarPath", mUserInfo.getAvatarFile().getAbsolutePath());
                    intent.setClass(this, BrowserViewPagerActivity.class);
                    startActivity(intent);
                }
            } else {
                final Dialog dialog = DialogCreator.createLoadingDialog(this, this.getString(R.string.jmui_loading));
                dialog.show();
                mUserInfo.getBigAvatarBitmap(new GetAvatarBitmapCallback() {
                    @Override
                    public void gotResult(int status, String desc, Bitmap bitmap) {
                        if (status == 0) {
                            mIsGetAvatar = true;
                            //缓存头像
                            NativeImageLoader.getInstance().updateBitmapFromCache(mUserInfo.getUserName(), bitmap);
                            Intent intent = new Intent();
                            intent.putExtra("browserAvatar", true);
                            intent.putExtra("avatarPath", mUserInfo.getUserName());
                            intent.setClass(FriendInfoActivity.this, BrowserViewPagerActivity.class);
                            startActivity(intent);
                        }
                        dialog.dismiss();
                    }
                });
            }
        }*/
    }

    private void updateUserInfo() {
       /* final Dialog dialog = DialogCreator.createLoadingDialog(FriendInfoActivity.this,
                FriendInfoActivity.this.getString(R.string.jmui_loading));
        dialog.show();*/
        if (TextUtils.isEmpty(mTargetId) && !TextUtils.isEmpty(mUserID)) {
            mTargetId = mUserID;
        }
        JMessageClient.getUserInfo(mTargetId, mTargetAppKey, new GetUserInfoCallback() {
            @Override
            public void gotResult(int responseCode, String responseMessage, UserInfo info) {
                //dialog.dismiss();
                if (responseCode == 0) {
                    //拉取好友信息时候要更新数据库中的nickName.因为如果对方修改了nickName我们是无法感知的.如果不在拉取信息
                    //时候更新数据库的话会影响到搜索好友的nickName, 注意要在没有备注名并且有昵称时候去更新.因为备注名优先级更高
                    new Update(FriendEntry.class).set("DisplayName=?", info.getDisplayName()).where("Username=?", mTargetId).execute();
                    new Update(FriendEntry.class).set("NickName=?", info.getNickname()).where("Username=?", mTargetId).execute();
                    new Update(FriendEntry.class).set("NoteName=?", info.getNotename()).where("Username=?", mTargetId).execute();

                    if (info.getAvatarFile() != null) {
                        new Update(FriendEntry.class).set("Avatar=?", info.getAvatarFile().getAbsolutePath()).where("Username=?", mTargetId).execute();
                    }
                    mUserInfo = info;

                    //用于会话名
                    mTitle = info.getNotename();//备注名
                    if (TextUtils.isEmpty(mTitle)) {
                        mTitle = info.getNickname();//昵称
                    }
                    //设置数据
                    initData(info);
                } else {
                    Toast.makeText(mContext,"数据更新失败",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
